package com.hashnode.controller;

import com.hashnode.cloudservice.PaymentHystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@Slf4j
@DefaultProperties(defaultFallback = "defaultHandler")//默认的容错方案
public class OrderController {


    @Resource
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/consumer/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id){
        String result = paymentHystrixService.paymentInfo_OK(id);
        return result;
    }

    //如果所调用的服务有错会调用默认的降级服务
    @GetMapping("/consumer/payment/hystrix/timeoutt/{id}")
    public String paymentInfo_OK2(@PathVariable("id") Integer id){
        String result = paymentHystrixService.paymentInfo_Tiemout(id);
        return result;
    }

    //    运行缓慢或出错则会进行服务降级
//    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
//            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000")
//    })
    //使用默认的容错
    @HystrixCommand
    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    public String paymentInfo_Tiemout(@PathVariable("id") Integer id){
        String result = paymentHystrixService.paymentInfo_Tiemout(id);
        return result;
    }

    //服务降级，兜底方案
    public String paymentInfo_TimeOutHandler(Integer id){
        return "线程池:" + Thread.currentThread().getName() + "consumer paymentInfo_TimeOutHandler,id" + id +"\t";
    }

    //服务降级的默认方法
    public String defaultHandler(){
        return "线程池:" + Thread.currentThread().getName() + "consumer defaultHandler";
    }

}
